package net.example.lesson5.lock;

import java.util.concurrent.locks.ReentrantLock;

public class FairReentrantLock {
    /**
     * true  公平锁
     * false  非公平锁
     */
    private static  final ReentrantLock lock = new ReentrantLock(true);

    public static void main(String[] args) {
        Thread[] threads = new Thread[10];
        for(int i=0;i<10;i++){
            threads[i] = new Thread(new FairLockTask());
        }
        for(int i=0;i<10;i++){
            threads[i].start();
        }
    }

    static void action(){
        try{
            lock.lock();
            System.out.println("线程："+Thread.currentThread().getName()+" 已经获得锁");
        }finally {
            lock.unlock();
        }
    }

    static class FairLockTask implements Runnable{
        @Override
        public void run() {
            System.out.println("线程："+Thread.currentThread().getName()+" 已经运行");
            action();
        }
    }
}
